package org.csu.mypetstore.controller;

import com.github.wxpay.sdk.WechatOrder;
import net.sf.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;

@Controller
@RequestMapping("/pay")
public class PayController {

    @GetMapping(produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] get(int orderId) {
        try{
            System.out.println("order received");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(Objects.requireNonNull(WechatOrder.order(0.01, orderId)), "png", bos);
            return bos.toByteArray();
        }
        catch (Exception e) {
            System.out.println("error");
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping
    @ResponseBody
    public String post(int orderId) {
        JSONObject jsonObject = new JSONObject();
        if(WechatOrder.getStatus(String.valueOf(orderId))){
            jsonObject.put("status", "OK");
        }
        else {
            jsonObject.put("status", "NOK");
            jsonObject.put("msg", "Order not paid yet");
        }
        return jsonObject.toString();
    }
}
